package io.github.springstudent.dekstop.client.core;

import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;

import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

/**
 * @author ZhouNing
 * @date 2024/12/9 10:53
 **/
public abstract class RemoteFrame extends JFrame {
    private JLabel titleLabel;
    private JTextField deviceCodeField;
    private JTextField passwordField;
    private JTextField remoteDeviceField;
    private JLabel controlledLabel;
    private JLabel closeSessionLabel;

    public RemoteFrame() {
        initFrame();
        initTitle();
        initPanel();
        this.setVisible(true);
    }

    /**
     * 初始化窗口
     */
    private void initFrame() {
        this.setUndecorated(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(600, 400);
        this.setLayout(new BorderLayout());
        this.setLocationRelativeTo(null);
    }

    /**
     * 初始化标题栏
     */
    private void initTitle() {
        JPanel titleBar = new JPanel(new BorderLayout());
        titleBar.setBorder(new EmptyBorder(10, 5, 10, 5));
        titleBar.setBackground(new Color(45, 45, 45));  // 深色标题栏

        titleLabel = new JLabel();
        titleLabel.setText("<html><font color='white'><b>远程桌面控制</b></font> <span style='color:#FF7043;'>（连接中）</span></html>");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        titleBar.add(titleLabel, BorderLayout.WEST);

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 5, 0));
        buttonPanel.setOpaque(false);
        JButton minimizeButton = createTitleBarButton("最小化(-)");
        minimizeButton.addActionListener(e -> this.setState(JFrame.ICONIFIED));
        JButton closeButton = createTitleBarButton("关闭(x)");
        closeButton.addActionListener(e -> System.exit(0));
        buttonPanel.add(minimizeButton);
        buttonPanel.add(closeButton);
        titleBar.add(buttonPanel, BorderLayout.EAST);
        MouseAdapter dragListener = new MouseAdapter() {
            private Point initialClick;

            @Override
            public void mousePressed(MouseEvent e) {
                initialClick = e.getPoint();
            }

            @Override
            public void mouseDragged(MouseEvent e) {
                int xMoved = e.getXOnScreen() - initialClick.x;
                int yMoved = e.getYOnScreen() - initialClick.y;
                setLocation(xMoved, yMoved);
            }
        };
        titleBar.addMouseListener(dragListener);
        titleBar.addMouseMotionListener(dragListener);
        this.add(titleBar, BorderLayout.NORTH);
    }

    /**
     * 创建标题栏按钮
     */
    private JButton createTitleBarButton(String text) {
        JButton button = new JButton(text);
        button.setFocusPainted(false);
        button.setBorder(BorderFactory.createEmptyBorder(5, 12, 5, 12));
        button.setBackground(new Color(70, 70, 70));  // 深色按钮
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        return button;
    }

    /**
     * 初始化面板
     */
    private void initPanel() {
        // 主面板改为左右布局
        JPanel mainPanel = new JPanel(new BorderLayout(20, 0)); // 增加左右间距
        mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20));

        // 左侧logo面板
        JPanel leftPanel = new JPanel();
        leftPanel.setPreferredSize(new Dimension(150, 0));
        leftPanel.setLayout(new BorderLayout());

        // 这里添加logo，实际使用时替换为您的logo图片
        JLabel logoLabel = new JLabel("LOGO", SwingConstants.CENTER);
        logoLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 24));
        logoLabel.setForeground(new Color(66, 165, 245));
        leftPanel.add(logoLabel, BorderLayout.CENTER);
        mainPanel.add(leftPanel, BorderLayout.WEST);

        // 右侧面板(上下布局)
        JPanel rightPanel = new JPanel();
        rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));

        // 上方当前设备信息面板
        JPanel currentDevicePanel = new JPanel(new GridBagLayout());
        currentDevicePanel.setBorder(BorderFactory.createTitledBorder("当前设备信息"));
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // 设备代码标签
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel deviceLabel = new JLabel("设备代码:");
        deviceLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        currentDevicePanel.add(deviceLabel, gbc);

        // 设备代码显示框
        gbc.gridx = 1;
        this.deviceCodeField = new JTextField(15);
        deviceCodeField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        deviceCodeField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(200, 200, 200)),
            BorderFactory.createEmptyBorder(8, 10, 8, 10)
        ));
        deviceCodeField.setEditable(false);
        currentDevicePanel.add(deviceCodeField, gbc);

        // 临时密码标签
        gbc.gridx = 0;
        gbc.gridy = 1;
        JLabel pwdLabel = new JLabel("临时密码:");
        pwdLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        currentDevicePanel.add(pwdLabel, gbc);

        // 临时密码输入框(可修改)
        gbc.gridx = 1;
        this.passwordField = new JTextField(15);
        passwordField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        passwordField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(200, 200, 200)),
            BorderFactory.createEmptyBorder(8, 10, 8, 10)
        ));
        passwordField.setEditable(true); // 允许修改密码
        currentDevicePanel.add(passwordField, gbc);

        // 复制密码按钮
        gbc.gridx = 2;
        JButton copyPwdBtn = new JButton("复制");
        styleCopyButton(copyPwdBtn);
        copyPwdBtn.addActionListener(e -> {
            String deviceCode = deviceCodeField.getText();
            String pwd = passwordField.getText();
            String copyText = "设备代码：" + deviceCode + "\n" + "连接密码：" + pwd;
            copyToClipboard(copyText);
        });
        currentDevicePanel.add(copyPwdBtn, gbc);

        rightPanel.add(currentDevicePanel);
        rightPanel.add(Box.createVerticalStrut(20)); // 增加间距

        // 下方连接面板
        JPanel connectPanel = new JPanel(new GridBagLayout());
        connectPanel.setBorder(BorderFactory.createTitledBorder("连接其他设备"));
        gbc = new GridBagConstraints();
        gbc.insets = new Insets(10, 10, 10, 10);
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.anchor = GridBagConstraints.WEST;

        // 远程设备输入框
        gbc.gridx = 0;
        gbc.gridy = 0;
        JLabel remoteLabel = new JLabel("设备代码:");
        remoteLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        connectPanel.add(remoteLabel, gbc);

        gbc.gridx = 1;
        this.remoteDeviceField = new JTextField(15);
        remoteDeviceField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        remoteDeviceField.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(200, 200, 200)),
            BorderFactory.createEmptyBorder(8, 10, 8, 10)
        ));
        remoteDeviceField.setEditable(true); // 允许修改远程设备代码
        connectPanel.add(remoteDeviceField, gbc);

        // 连接按钮
        gbc.gridx = 2;
        JButton connectButton = new JButton("连接");
        connectButton.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        connectButton.setBackground(new Color(66, 165, 245));
        connectButton.setForeground(Color.WHITE);
        connectButton.setBorder(BorderFactory.createEmptyBorder(5, 15, 5, 15));
        connectButton.addActionListener(e -> {
            // 原有连接逻辑保持不变
            if (StrUtil.isEmpty(remoteDeviceField.getText())) {
                showMessageDialog("请输入其他设备代码", JOptionPane.ERROR_MESSAGE);
            } else if (remoteDeviceField.getText().equals(deviceCodeField.getText())) {
                showMessageDialog("不可连接自己", JOptionPane.ERROR_MESSAGE);
            } else if (!ReUtil.isMatch("^[a-zA-Z0-9]+$", remoteDeviceField.getText())) {
                showMessageDialog("其他设备代码只能为数字与字母的组合", JOptionPane.ERROR_MESSAGE);
            } else {
                openRemoteScreen(remoteDeviceField.getText());
            }
        });
        connectPanel.add(connectButton, gbc);

        rightPanel.add(connectPanel);

        // 控制状态面板
        JPanel statusPanel = new JPanel(new GridBagLayout());
        statusPanel.setBorder(new EmptyBorder(20, 0, 0, 0));
        GridBagConstraints gbc2 = new GridBagConstraints();
        gbc2.fill = GridBagConstraints.HORIZONTAL;
        gbc2.anchor = GridBagConstraints.CENTER;
        gbc2.gridwidth = 3;
        gbc2.insets = new Insets(10, 10, 10, 10);

        // 被控制状态标签
        this.controlledLabel = new JLabel("正在被远程控制中...");
        controlledLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 13));
        controlledLabel.setForeground(new Color(244, 67, 54));
        controlledLabel.setVisible(false);
        statusPanel.add(controlledLabel, gbc2);

        // 断开连接标签
        this.closeSessionLabel = new JLabel("<html><u>断开连接</u></html>");
        closeSessionLabel.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        closeSessionLabel.setForeground(new Color(33, 150, 243));
        closeSessionLabel.setVisible(false);
        closeSessionLabel.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                closeRemoteScreen(deviceCodeField.getText());
            }
        });
        statusPanel.add(closeSessionLabel, gbc2);
        rightPanel.add(statusPanel);

        mainPanel.add(rightPanel, BorderLayout.CENTER);

        this.add(mainPanel, BorderLayout.CENTER);
    }

    public void showMessageDialog(Object msg, int messageType) {
        JOptionPane.showMessageDialog(this, msg, "提示", messageType);
    }

    public abstract void openRemoteScreen(String remoteName);

    public abstract void closeRemoteScreen();

    public abstract void closeRemoteScreen(String deviceCode);

    public final void setDeviceCodeAndPassword(String deviceCode, String password) {
        this.deviceCodeField.setText(deviceCode);
        this.passwordField.setText(password);
    }

    public final void updateConnectionStatus(boolean connected) {
        if (connected) {
            titleLabel.setText("<html><font color='white'><b>远程桌面控制</b></font> <span style='color:#4CAF50;'>（已就绪）</span></html>");
        } else {
            titleLabel.setText("<html><font color='white'><b>远程桌面控制</b></font> <span style='color:#FF7043;'>（连接中）</span></html>");
        }
    }

    public final void setControlledAndCloseSessionLabelVisible(boolean flag) {
        this.controlledLabel.setVisible(flag);
        this.closeSessionLabel.setVisible(flag);
    }

    /**
     * 复制按钮样式
     *
     * @param button 复制按钮
     */
    private void styleCopyButton(JButton button) {
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        button.setBackground(new Color(245, 245, 245));
        button.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(200, 200, 200)),
            BorderFactory.createEmptyBorder(5, 15, 5, 15)
        ));
        button.setFocusPainted(false);
    }

    /**
     * 复制文本到剪贴板
     *
     * @param text 要复制的文本
     */
    private void copyToClipboard(String text) {
        StringSelection selection = new StringSelection(text);
        Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
        clipboard.setContents(selection, selection);
        showMessageDialog("已复制到剪贴板", JOptionPane.INFORMATION_MESSAGE);
    }
}